package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Transactional
    @Override
    public User findByUsername(String username) {
        //先查基本信息
        User user = userDao.selectByUsername(username);
        if (null == user) {
            //用户不存在
            return null;
        }
        //根据用户ID查角色信息
        List<Role> roles = roleDao.selectByUserId(user.getId());
        for (Role role : roles) {
            //根据角色ID查权限信息
            List<Permission> permissions = permissionDao.selectByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        return user;
    }

    /**
     * 分页展示user
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        log.info("[用户-分页查询]data:{}", queryPageBean);
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //分页查询数据库
        Page<User> page = userDao.selectByConditon(queryPageBean.getQueryString());

        //分装分页查询
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void add(User user , Integer[] roleIds) {
        //判断user是否存在
        User selectUser = userDao.selectByUsername(user.getUsername());
        if (null != selectUser) {
            throw new BusinessRuntimeException("当前用户名已被占用，请您更换");
        }
        //插入基本数据
        userDao.add(user);
        //逐条插入关系表数据
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(), roleId);
        }
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {

        return userDao.findById(id);
    }


    @Override
    public List<Integer> findRoleIdByUserId(Integer id) {

        return userDao.findRoleIdByUserId(id);
    }

    /**
     * 编辑用户
     * @param user
     */
    @Override
    @Transactional
    public void edit(User user,Integer[] roleIds) {
        //1.更新用户
        userDao.update(user);
        //2更新关联关系
        //2.1删除原有关系
        userDao.deleteUserAndRoleByUserId(user.getId());
        //2.2加入当前关系
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(),roleId);
        }
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    @Transactional
    public void delevte(Integer id) {
        try {
            userDao.delete(id);
        }catch (Exception e){
            throw new BusinessRuntimeException("该用户下存在角色权限，不能删除");
        }

    }
}
